#!/bin/bash
# -*- coding: utf-8 -*-
# 新闻日报系统一键启动脚本

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 打印横幅
print_banner() {
    echo "============================================================"
    echo "📰 MorningByte 新闻日报系统 - 一键启动"
    echo "============================================================"
    echo "启动时间: $(date '+%Y-%m-%d %H:%M:%S')"
    echo "============================================================"
}

# 检查Python环境
check_python() {
    print_info "检查Python环境..."
    
    if command -v python3 &> /dev/null; then
        PYTHON_CMD="python3"
    elif command -v python &> /dev/null; then
        PYTHON_CMD="python"
    else
        print_error "未找到Python环境，请先安装Python 3.7+"
        exit 1
    fi
    
    # 检查Python版本
    PYTHON_VERSION=$($PYTHON_CMD --version 2>&1 | cut -d' ' -f2)
    print_success "找到Python版本: $PYTHON_VERSION"
}

# 检查依赖包
check_dependencies() {
    print_info "检查依赖包..."
    
    local missing_packages=()
    
    # 检查每个依赖包
    if ! $PYTHON_CMD -c "import openai" 2>/dev/null; then
        missing_packages+=("openai")
    fi
    
    if ! $PYTHON_CMD -c "import requests" 2>/dev/null; then
        missing_packages+=("requests")
    fi
    
    if ! $PYTHON_CMD -c "import feedparser" 2>/dev/null; then
        missing_packages+=("feedparser")
    fi
    
    if ! $PYTHON_CMD -c "import bs4" 2>/dev/null; then
        missing_packages+=("beautifulsoup4")
    fi
    
    if ! $PYTHON_CMD -c "import lxml" 2>/dev/null; then
        missing_packages+=("lxml")
    fi
    
    if ! $PYTHON_CMD -c "import schedule" 2>/dev/null; then
        missing_packages+=("schedule")
    fi
    
    if [ ${#missing_packages[@]} -gt 0 ]; then
        print_warning "缺少以下依赖包: ${missing_packages[*]}"
        print_info "正在安装依赖包..."
        
        if [ -f "requirements.txt" ]; then
            $PYTHON_CMD -m pip install -r requirements.txt
            print_success "依赖包安装完成"
        else
            print_error "未找到requirements.txt文件"
            exit 1
        fi
    else
        print_success "所有依赖包已安装"
    fi
}

# 检查配置文件
check_config() {
    print_info "检查配置文件..."
    
    if [ ! -f "email_config.py" ]; then
        print_warning "未找到配置文件，启动配置向导..."
        $PYTHON_CMD setup_email.py
    fi
    
    # 验证配置
    if $PYTHON_CMD -c "from email_config import validate_config; errors = validate_config(); exit(0 if not errors else 1)" 2>/dev/null; then
        print_success "配置文件验证通过"
    else
        print_error "配置文件验证失败，请检查email_config.py"
        print_info "您可以运行以下命令重新配置:"
        echo "  $PYTHON_CMD setup_email.py"
        exit 1
    fi
}

# 创建必要目录
create_directories() {
    print_info "创建必要目录..."
    
    mkdir -p logs
    mkdir -p data
    
    print_success "目录创建完成"
}

# 启动服务
start_service() {
    print_info "启动新闻日报服务..."
    
    # 显示配置信息
    print_info "当前配置:"
    $PYTHON_CMD -c "
from email_config import get_config_info
info = get_config_info()
print(f'  发送邮箱: {info[\"sender_email\"]}')
print(f'  接收邮箱: {info[\"recipient_email\"]}')
print(f'  发送时间: 每天 {info[\"send_time\"]}')
print(f'  RSS源: {info[\"rss_url\"]}')
"
    
    print_info "服务启动中..."
    print_warning "按 Ctrl+C 停止服务"
    print_info "日志文件: logs/scheduler_$(date +%Y%m%d).log"
    
    # 启动调度器
    $PYTHON_CMD start_daily_news.py
}

# 主函数
main() {
    print_banner
    
    # 检查环境
    check_python
    check_dependencies
    check_config
    create_directories
    
    # 启动服务
    start_service
}

# 捕获中断信号
trap 'print_info "服务已停止"; exit 0' INT TERM

# 运行主函数
main "$@"
